<template>
  <div class="supplier-container base-page-container">
    <!-- 搜索区域 -->
    <common-search
      v-model="searchForm"
      :search-items="searchItemsConfig"
      @search="handleSearch"
      @reset="fetchTableData"
    >
      <!-- 自定义插槽示例 -->
      <template #customSlot="{ form }">
        <!-- 这里可以放置自定义搜索组件 -->
        <el-select v-model="form.customField" placeholder="自定义字段" style="width: 230px">
          <el-option label="选项1" value="1" />
          <el-option label="选项2" value="2" />
        </el-select>
      </template>
    </common-search>
    
    <!-- 操作按钮区域 -->
    <action-buttons
      :action-permissions="actionPermissions"
      add-type="success"
      :export-type="themeType" 
      :import-type="themeType"
      :enable-type="themeType"
      :disable-type="themeType"
      @add="handleAdd"
      @export="handleExport"
      @import="handleImport"
      @enable="handleEnable"
      @disable="handleDisable"
    />
    
    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="supplier-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 状态列的自定义插槽 -->
      <template #status="{ row }">
        <el-tag :type="row.status === '启用' ? 'success' : 'info'">
          {{ row.status }}
        </el-tag>
      </template>
      
      <!-- 操作列 -->
      <template #operation="{ row }">
        <theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
        <theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
        <theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
      </template>
    </custom-table>
    
    <!-- 供应商信息弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增供应商' : '编辑供应商'"
      width="750px"
      destroy-on-close
      class="base-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="supplierFormRules"
        label-width="120px"
        class="base-form"
      >
        <div class="form-row">
          <el-form-item label="供应商编号" prop="code">
            <el-input v-model="supplierForm.code" placeholder="请输入供应商编号"></el-input>
          </el-form-item>
          <el-form-item label="供应商名称" prop="name">
            <el-input v-model="supplierForm.name" placeholder="请输入供应商名称"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="供应商等级" prop="level">
            <el-select v-model="supplierForm.level" placeholder="请选择供应商等级" style="width: 100%">
              <el-option label="请选择供应商等级" value=""></el-option>
              <el-option label="一级供应商" value="一级供应商"></el-option>
              <el-option label="二级供应商" value="二级供应商"></el-option>
              <el-option label="三级供应商" value="三级供应商"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商标签" prop="tag">
            <el-select v-model="supplierForm.tag" placeholder="请选择供应商标签" style="width: 100%">
              <el-option label="请选择供应商标签" value=""></el-option>
              <el-option label="优质供应商" value="优质供应商"></el-option>
              <el-option label="一般供应商" value="一般供应商"></el-option>
              <el-option label="重点供应商" value="重点供应商"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row" style="border-bottom: solid 1px #eee;">
          <el-form-item label="货主" prop="owner">
            <el-select v-model="supplierForm.owner" placeholder="请选择货主" style="width: 50%">
              <el-option label="请选择货主" value=""></el-option>
              <el-option label="货主A" value="货主A"></el-option>
              <el-option label="货主B" value="货主B"></el-option>
              <el-option label="货主C" value="货主C"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row full-width">
          <el-form-item label="供应商地址" prop="region">
            <el-select v-model="supplierForm.region" placeholder="请选择所在区域" style="width: 50%">
              <el-option label="请选择所在区域" value=""></el-option>
              <el-option label="华东地区" value="华东地区"></el-option>
              <el-option label="华南地区" value="华南地区"></el-option>
              <el-option label="华北地区" value="华北地区"></el-option>
              <el-option label="西南地区" value="西南地区"></el-option>
              <el-option label="西北地区" value="西北地区"></el-option>
            </el-select>
          </el-form-item>
        </div>
		
		<div class="form-row full-width">
		  <el-form-item label="详细地址" prop="address" class="full-width-item">
		    <el-input v-model="supplierForm.address" placeholder="请输入详细地址" type="textarea" rows="3"></el-input>
		  </el-form-item>
		</div>
        
        <div class="form-row">
          <el-form-item label="邮编" prop="zipCode">
            <el-input v-model="supplierForm.zipCode" placeholder="请输入邮编"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="手机号" prop="contactPhone">
            <el-input v-model="supplierForm.contactPhone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="固话" prop="telephone">
            <el-input v-model="supplierForm.telephone" placeholder="请输入固话"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row full-width">
          <el-form-item label="备注" prop="remark" class="full-width-item">
            <el-input v-model="supplierForm.remark" placeholder="请输入备注" type="textarea" rows="3"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <dialog-footer 
          cancel-text="取消"
          confirm-text="确定"
          @cancel="dialogVisible = false" 
          @confirm="submitForm" 
        />
      </template>
    </el-dialog>
    
    <!-- 日志弹窗 -->
    <log-dialog
      v-model:visible="logDialogVisible"
      :log-data="logData"
      :total="logPagination.total"
      :current-page="logPagination.currentPage"
      :page-size="logPagination.pageSize"
      @size-change="handleLogSizeChange"
      @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useTheme } from '@/hooks/useTheme'
import { RegionCascader } from '@/components/common'

// 使用主题组合API
const { themeType } = useTheme()

// 判断是否开发环境
const isDevelopment = computed(() => {
  return import.meta.env.MODE === 'development'
})

// 搜索项配置列表
const searchItemsConfig = [
  {
    label: '供应商编号',
    prop: 'code',
    type: 'el-input',
    placeholder: '请输入供应商编号',
    defaultVisible: true
  },
  {
    label: '供应商名称',
    prop: 'name',
    type: 'el-input',
    placeholder: '请输入供应商名称',
    defaultVisible: true
  },
  {
    label: '状态',
    prop: 'status',
    type: 'el-select',
    placeholder: '请选择状态',
    defaultVisible: true,
    options: [
      { label: '请选择状态', value: '' },
      { label: '启用', value: '启用' },
      { label: '停用', value: '停用' }
    ]
  },
  {
    label: '创建日期',
    prop: 'createDate',
    type: 'el-date-picker',
    placeholder: '请选择创建日期',
    defaultVisible: true,
    dateType: 'date',
    format: 'YYYY-MM-DD',
    valueFormat: 'YYYY-MM-DD'
  },
  {
    label: '货主',
    prop: 'owner',
    type: 'el-select',
    placeholder: '请选择货主',
    defaultVisible: false,
    options: [
      { label: '请选择货主', value: '' },
      { label: '货主A', value: '货主A' },
      { label: '货主B', value: '货主B' },
      { label: '货主C', value: '货主C' }
    ]
  },
  {
    label: '联系人',
    prop: 'contactPerson',
    type: 'el-input',
    placeholder: '请输入联系人',
    defaultVisible: false
  },
  {
    label: '联系电话',
    prop: 'contactPhone',
    type: 'el-input',
    placeholder: '请输入联系电话',
    defaultVisible: false
  },
  {
    label: '日期范围',
    prop: 'dateRange',
    type: 'el-date-picker-range',
    defaultVisible: false,
    format: 'YYYY-MM-DD',
    valueFormat: 'YYYY-MM-DD'
  },
  {
    label: '自定义字段',
    prop: 'customField',
    type: 'slot',
    slotName: 'customSlot',
    defaultVisible: false
  }
]

// 搜索表单数据
const searchForm = reactive({
  code: '',
  name: '',
  status: '',
  createDate: '',
  owner: '',
  contactPerson: '',
  contactPhone: '',
  dateRange: [],
  customField: ''
})

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 表格加载状态
const tableLoading = ref(false)

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 分页大小变更事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 页码变更事件
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  tableLoading.value = true
  
  // 构造查询参数
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  
  // 处理日期范围
  if (params.dateRange && params.dateRange.length === 2) {
    params.startDate = params.dateRange[0]
    params.endDate = params.dateRange[1]
    delete params.dateRange
  }
  
  console.log('查询参数:', params)
  
  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    tableData.value = Array.from({ length: pagination.pageSize }).map((_, index) => ({
      id: index + 1 + (pagination.currentPage - 1) * pagination.pageSize,
      code: `GYS${10000 + index}`,
      name: `供应商${String.fromCharCode(65 + index % 26)}`,
      owner: '货主A',
      status: index % 3 ? '启用' : '停用',
      contactPerson: '王阳明',
      contactPhone: '13587584785',
      contactAddress: '浙江省杭州市西湖区西湖大道XX路',
      remark: index % 2 ? '优质供应商' : ''
    }))
    
    tableLoading.value = false
  }, 300)
}

// 选中的行数据
const selectedRows = ref([])

// 表格多选事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 对话框可见性
const dialogVisible = ref(false)

// 对话框类型：add-新增, edit-编辑
const dialogType = ref('add')

// 表单引用
const supplierFormRef = ref(null)

// 供应商表单数据
const supplierForm = reactive({
  code: '',
  name: '',
  level: '',
  tag: '',
  owner: '',
  region: '',
  address: '',
  zipCode: '',
  contactPerson: '',
  contactPhone: '',
  telephone: '',
  remark: ''
})

// 表单校验规则
const supplierFormRules = {
  code: [
    { required: true, message: '请输入供应商编号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  owner: [
    { required: true, message: '请选择货主', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 新增按钮事件
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑按钮事件
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetForm()
  
  // 填充表单数据
  Object.keys(supplierForm).forEach(key => {
    if (row[key] !== undefined) {
      supplierForm[key] = row[key]
    }
  })
  
  dialogVisible.value = true
}

// 查看按钮事件
const handleView = (row) => {
  ElMessage.info(`查看供应商: ${row.name}`)
}

// 日志弹窗可见性
const logDialogVisible = ref(false)

// 日志数据
const logData = ref([])

// 日志分页数据
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 查看日志按钮事件
const handleLog = (row) => {
  logDialogVisible.value = true
  fetchLogData(row)
}

// 获取日志数据
const fetchLogData = (row) => {
  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    const currentDate = '2024-01-01 00:00:00'
    logData.value = [
      {
        id: 1,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `修改供应商 [${row.name}]`
      },
      {
        id: 2,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `新增供应商 [${row.name}]`
      },
      {
        id: 3,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 4,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 5,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 6,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      }
    ]
    
    logPagination.total = 6
  }, 300)
}

// 日志分页大小变更事件
const handleLogSizeChange = (val) => {
  logPagination.pageSize = val
  // 重新获取日志数据
}

// 日志页码变更事件
const handleLogCurrentChange = (val) => {
  logPagination.currentPage = val
  // 重新获取日志数据
}

// 删除按钮事件
const handleDelete = (row) => {
  let confirmText
  if (row) {
    confirmText = `确定要删除供应商 ${row.name} 吗?`
  } else {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请至少选择一个供应商')
      return
    }
    confirmText = `确定要删除选中的 ${selectedRows.value.length} 个供应商吗?`
  }
  
  ElMessageBox.confirm(confirmText, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除接口
    ElMessage.success('删除成功')
    fetchTableData()
  }).catch(() => {})
}

// 启用按钮事件
const handleEnable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个供应商')
    return
  }
  
  ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个供应商吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用启用接口
    ElMessage.success('启用成功')
    fetchTableData()
  }).catch(() => {})
}

// 停用按钮事件
const handleDisable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个供应商')
    return
  }
  
  ElMessageBox.confirm(`确定要停用选中的 ${selectedRows.value.length} 个供应商吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用停用接口
    ElMessage.success('停用成功')
    fetchTableData()
  }).catch(() => {})
}

// 导出按钮事件
const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 导入按钮事件
const handleImport = () => {
  ElMessage.success('导入功能开发中')
}

// 重置表单
const resetForm = () => {
  Object.keys(supplierForm).forEach(key => {
    supplierForm[key] = ''
  })
  
  if (supplierFormRef.value) {
    supplierFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  if (!supplierFormRef.value) return
  
  supplierFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用接口保存数据
      const message = dialogType.value === 'add' ? '新增成功' : '编辑成功'
      
      // 模拟提交
      setTimeout(() => {
        ElMessage.success(message)
        dialogVisible.value = false
        fetchTableData()
      }, 300)
    } else {
      return false
    }
  })
}

// 权限控制数据 - 默认权限设置
const actionPermissions = reactive({
  add: true,      // 新增权限
  export: true,   // 导出权限
  import: true,   // 导入权限
  enable: true,   // 启用权限
  disable: true   // 停用权限
})

// 表格操作权限 - 默认权限设置
const tablePermissions = reactive({
  edit: true,
  view: true,
  log: true
})

// 表格列配置
const tableColumns = ref([
  { prop: 'code', label: '供应商编码ID', width: '120', minWidth: '120', visible: true },
  { prop: 'name', label: '供应商名称', width: '120', minWidth: '120', visible: true },
  { prop: 'owner', label: '货主', width: '100', minWidth: '100', visible: true },
  { prop: 'status', label: '状态', width: '80', minWidth: '80', visible: true },
  { prop: 'contactPerson', label: '联系人', width: '100', minWidth: '100', visible: true },
  { prop: 'contactPhone', label: '手机号', width: '120', minWidth: '120', visible: true },
  { prop: 'contactAddress', label: '联系地址', minWidth: '200', visible: true },
  { prop: 'remark', label: '备注', width: '150', minWidth: '150', visible: true },
  { prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
])

// 页面初始化
onMounted(async () => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
</style> 